﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MvvmEx.Dispatchers;
using MvvmEx.Enums;

namespace MvvmEx.Controls.Messager
{
    /// <summary>
    /// 消息提示类
    /// </summary>
    public static class NotifyManager
    {
        private static List<NotifyMsg> _notifyQueue;
        private static Timer _timer;
        private static readonly int _dueTime = 1000;

        static NotifyManager()
        {
            _notifyQueue = new List<NotifyMsg>();
        }

        public static void Init()
        {
            _timer = new Timer(NotifyMsgLoop, null, _dueTime, Timeout.Infinite);
        }

        public static void ShowNotify(NotifyMsg notifyMsg)
        {
            _notifyQueue.Add(notifyMsg);
        }

        private static void NotifyMsgLoop(object obj)
        {
            if (_notifyQueue.Any())
            {
                //移除已经关闭的
                _notifyQueue.Where(x => x.Status == NotifyMsgStatusDefine.Close).ToList().ForEach(x =>
                    {
                        _notifyQueue.Remove(x);
                    });

                //是否有需要显示的
                if (_notifyQueue.All(x => x.Status != NotifyMsgStatusDefine.Showing))
                {
                    var notifyMsg = _notifyQueue.FirstOrDefault();

                    if (notifyMsg != null)
                    {
                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            var notifyMessageBox = new NotifyMessageBox(notifyMsg);

                            notifyMessageBox.Show();
                        });
                    }
                }
            }

            _timer.Change(_dueTime, Timeout.Infinite);
        }
    }
}